const { Op, where } = require("sequelize");
const { DictItem } = require("../../../../models");
const utils = require("../../../../utils");
const dictService = require("../../dict/service/DictServiceImpl");
module.exports = {
  // 创建/编辑字典
  async saveOrUpdate(req, res, next) {
    try {
      const { id } = req.body;
      id
        ? this.updateDictItem(req, res, next)
        : this.saveDictItem(req, res, next);
    } catch (error) {
      next(error);
    }
  },

  // 创建字典
  async saveDictItem(req, res, next) {
    try {
      await this.checkDictItemValue(req, next);
      const user = await DictItem.create(req.body);
      return user ? res.cc(null, "成功创建") : res.err("创建失败");
    } catch (error) {
      next(error);
    }
  },

  // 更新字典
  async updateDictItem(req, res, next) {
    try {
      // 1、校验字典是否存在
      await this.checkDictItemValue(req, next);
      const dictItem = await DictItem.findByPk(req.body.id);
      // 2、组装参数
      await utils.assignEditValue(dictItem, req.body);
      // 3、执行更新
      const result = await dictItem.save();
      return result ? res.cc(null, "更新成功") : res.err("更新失败");
    } catch (error) {
      next(error);
    }
  },

  // 检查要存储的value是否存在
  async checkDictItemValue(req, next) {
    const { id, dictId, value } = req.body;
    const dictItem = await dictService.checkDictInfo(dictId, next);
    if (!dictItem) throw new Error("请传入合适的字典项id");
    const list = await DictItem.findAll({
      where: {
        dictId,
        value,
      },
    });
    if (list.length > 1) {
      throw new Error(
        `数据库中存在多个dictId为${dictId}且value为${value}的数据,请联系管理员处理`
      );
    } else if (list.length === 1) {
      const item = list?.[0]?.dataValues;
      if (!id || item.id !== id) {
        throw new Error("字典项值已存在");
      }
    }
  },

  // 批量删除
  async batchDelete(req, res, next) {
    try {
      const { ids } = req.body;
      if (!ids || ids?.length === 0) {
        throw new Error("ids不能为空");
      }
      const result = await DictItem.destroy({
        where: {
          id: {
            [Op.in]: ids,
          },
        },
      });
      return result ? res.cc(null, "删除成功") : res.err("删除失败");
    } catch (error) {
      next(error);
    }
  },

  // 更改当前项的status
  async changeStatus(req, res, next) {
    try {
      const { id, status } = req.body;
      if (!id) return res.err("请输入id");

      const dictItem = await DictItem.findByPk(id);
      if (!dictItem) {
        return res.err("字典项不存在");
      }
      dictItem.status = status;
      const result = await dictItem.save();
      return result ? res.cc(status, "状态更新成功") : res.err("删除失败");
    } catch (error) {
      next(error);
    }
  },

  // 获取字典列表
  async getDictList(req, res, next) {
    try {
      const params = await this.getSearchParams(req);
      const dicts = await DictItem.findAll(params);
      return res.cc(dicts);
    } catch (error) {
      next(error);
    }
  },
};
